#!/bin/bash
# PostgreSQL Database Viewer - macOS Launcher
# This script launches the database viewer on macOS with proper Python detection

echo "🚀 Starting PostgreSQL Database Viewer..."
echo

# Check for Python installations
PYTHON_CMD=""

# Try different Python commands
for cmd in python3 python3.11 python3.10 python3.9 python3.8 python; do
    if command -v $cmd &> /dev/null; then
        PYTHON_VERSION=$($cmd --version 2>&1)
        echo "✅ Found Python: $cmd ($PYTHON_VERSION)"
        PYTHON_CMD=$cmd
        break
    fi
done

# If no Python found, provide installation instructions
if [ -z "$PYTHON_CMD" ]; then
    echo "❌ Error: No Python installation found"
    echo
    echo "Please install Python 3.7 or higher:"
    echo "1. Using Homebrew: brew install python3"
    echo "2. Using official installer: https://www.python.org/downloads/"
    echo "3. Using pyenv: brew install pyenv && pyenv install 3.11.0"
    echo
    read -p "Press Enter to exit..."
    exit 1
fi

# Check if required files exist
if [ ! -f "tkinter_viewer.py" ]; then
    echo "❌ Error: tkinter_viewer.py not found"
    echo "Please ensure you are in the correct directory"
    exit 1
fi

# Check if requirements.txt exists
if [ ! -f "requirements.txt" ]; then
    echo "⚠️  Warning: requirements.txt not found"
    echo "Some features may not work properly"
else
    # Install dependencies if needed
    echo "📦 Checking dependencies..."
    $PYTHON_CMD -m pip install -r requirements.txt --quiet
    if [ $? -eq 0 ]; then
        echo "✅ Dependencies are up to date"
    else
        echo "⚠️  Warning: Some dependencies may not be installed properly"
    fi
fi

# Launch the application
echo "🎯 Launching Database Viewer..."
echo "Using Python: $PYTHON_CMD"
echo

$PYTHON_CMD tkinter_viewer.py

# Check exit status
if [ $? -ne 0 ]; then
    echo
    echo "❌ An error occurred. Common solutions:"
    echo "1. Make sure PostgreSQL is running: brew services start postgresql"
    echo "2. Check database connection settings"
    echo "3. Verify Python dependencies: pip3 install -r requirements.txt"
    echo
    read -p "Press Enter to exit..."
fi
